package edu.mbb.cloud.nacos.listen;

import org.springframework.cglib.core.Constants;

import java.util.concurrent.CopyOnWriteArrayList;

/**、
 * 监听的单元
 */
public class CacheData {

    /**
     * group
     */
    private String group;
    /**
     * 文件名
     */
    private String dataId;
    /**
     * 命名空间
     */
    private String tenant;

    private String md5;
    //内容 为了生成md5
    private String content;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    /**
     * nacos 用了这个数组。适用于读多写少的场景。
     * 很好
     */
    private CopyOnWriteArrayList<Listener> listeners;


    public boolean checkListenerMd5(){
        String nowMd5= getMd5String(content);
        if(!nowMd5.equalsIgnoreCase(this.md5)){
            this.md5=nowMd5;
            for (Listener listener : listeners) {
                listener.receiveConfigInfo(content);
            }
            return true;
        }
        return false;
    }

    static public String getMd5String(String config) {
        return (null == config) ? null: MD5.getInstance().getMD5String(config);
    }
    public CacheData(String tenant, String dataId, String group,String content){
        this.tenant=tenant;
        this.dataId=dataId;
        this.group=group;
        this.content=content;
        this.md5 = getMd5String(content);
        listeners=new CopyOnWriteArrayList<>();
    }
    public String getMd5() {
        return md5;
    }

    public void setMd5(String md5) {
        this.md5 = md5;
    }

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }

    public String getDataId() {
        return dataId;
    }

    public void setDataId(String dataId) {
        this.dataId = dataId;
    }

    public String getTenant() {
        return tenant;
    }

    public void setTenant(String tenant) {
        this.tenant = tenant;
    }

    public void addListener(Listener listener){
        listeners.add(listener);
    }

}
